<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus'
// 文章题目
let title = ref('')
//文章内容
let content = ref('')
//创建时间
let createTime = ref('')
let pageNum = ref(1)
let pageSize = ref(10)
let total = ref(5)
let tableData = reactive([])

let dialogVisible = ref(false)
let dialogVisible1 = ref(false)
let form = reactive({})
let status = reactive({})

onMounted(() => {
   load()
})
function load() { // 加载数据，其实就是向后台发请求
  // const formattedDate = createTime.value ? createTime.value.toISOString().split('T')[0] : '';
  const formattedDate = createTime.value
  ? createTime.value.toLocaleDateString('default', { timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone })
  : '';
  const cTime = convertDateWithLeadingZeros(formattedDate)
  let url = 'http://localhost/article/articlePage?pageNum=' + pageNum.value + '&pageSize=' + pageSize.value + '&title=' + title.value + '&content=' + content.value + '&createTime=' + cTime
  axios.get(url)
    .then(function (response) {
      let records = response.data.data.records
      // 清空 tableData数组
      tableData.length = 0
      tableData.push(...records)
      total.value = response.data.data.total
    })
    .catch(function (error) {
      console.log(error);
    });
}

function onSearch() {
  load()
}

// 处理时区问题的
function convertDateWithLeadingZeros(dateWithSlash) {
    if (typeof dateWithSlash === 'string' && dateWithSlash) {
        // 分割字符串并使用map确保每个部分都有两位，不足补0，然后再用短横线连接
        let parts = dateWithSlash.split('/');
        return parts.map(part => part.padStart(2, '0')).join('-');
    }
    return dateWithSlash;
}

function handleSizeChange(num) {
  pageSize.value = num
  load()
}


function handleCurrentChange(num) {
  pageNum.value = num
  load()
}

function save() {
  // console.log(form);
  // 1. 将form数据发送到后台存数据库(post请求)
  axios.post('http://localhost/article/save', form)
    .then(function (response) {
      console.log(response.data);
      if (response.data.code == 20000) {       
        ElMessage({
          message: response.data.message,
          type: 'success',
        })
        load()
      }
    })
    .catch(function (error) {
      console.log(error);
    });

  // 2. 关闭el-dialog
  dialogVisible.value = false
}


function updateArticleStatus(enabled,id) {
  status.enabled = enabled
  status.id = id
  axios.post('http://localhost/article/update', status)
    .then(function (response) {
      console.log(response.data);
      if (response.data.code == 20000) {       
        ElMessage({
          message: response.data.message,
          type: 'success',
        })
        load()
      }
    })
    .catch(function (error) {
      console.log(error);
    });

  // 2. 关闭el-dialog
  dialogVisible.value = false
}

const rowClick = (row) => {
  // 当用户点击表格的某一行时，将该行的数据赋值给form
  form.title = row.title;
  form.content = row.content;
  form.id = row.id
};

function newArticle(){
  form.title = ''
  form.content = ''
  form.id = ''
  dialogVisible.value = true;
}


function edit() {
  axios.post('http://localhost/article/edit', form)
    .then(function (response) {
      console.log(response.data);
      if (response.data.code == 20000) {       
        ElMessage({
          message: response.data.message,
          type: 'success',
        })
        load()
      }
    })
    .catch(function (error) {
      console.log(error);
    });

  // 2. 关闭el-dialog
  dialogVisible1.value = false
}

</script>

<template>
  <div style="display: flex; flex-direction: column;">
    

    <!--  搜索区域 -->
    <div style="margin: 10px 0" >
  
      <el-form :inline="true" :model="content" class="demo-form-inline">
        <el-form-item label="文章题目">
            <el-input v-model="title" placeholder="文章题目"></el-input>
        </el-form-item>

        <el-form-item label="文章内容">
            <el-input v-model="content" placeholder="文章内容"></el-input>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-col :span="21">
            <el-date-picker type="date" placeholder="选择日期" v-model="createTime" style="width: 100%;"></el-date-picker>
          </el-col>
        </el-form-item>

        <el-form-item style="margin-right: auto;">
            <el-button type="primary" @click="onSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    
     <!-- 新增文章 -->
     <el-button type="primary" @click="newArticle" style="width: 70px;">发表文章</el-button>
    

    <!-- 数据展示 -->
    <el-table :data="tableData" style="width: 100%" @row-click="rowClick">
      <el-table-column label="序号" width="180">
        <template #default="scope">
            {{ scope.$index + 1 }} 
        </template>
      </el-table-column>
      <el-table-column prop="title" label="文章题目" width="180" />
      <el-table-column prop="content" label="文章内容" width="120">
        <template #default="scope">
            <div :title="scope.row.content" style="display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis;">
                {{ scope.row.content }}
            </div>
        </template>
       </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="scope">
          <span v-if="scope.row.enabled === 1"><el-button type="primary" @click="updateArticleStatus(0,scope.row.id)" style="width: 70px;">上架文章</el-button></span>
          <span v-else><el-button type="primary" @click="updateArticleStatus(1,scope.row.id)" style="width: 70px;">下架文章</el-button></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <el-button type="primary" @click="dialogVisible1 = true" style="width: 70px;">修改文章</el-button>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin: 10px 0">
      <el-pagination v-model:currentPage="pageNum" v-model:page-size="pageSize" :page-sizes="[5, 10, 50, 100]"
        :small="small" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    
    <!-- 新增 -->
    <el-dialog v-model="dialogVisible" title="发表文章" width="30%">
      <el-form :model="form" label-width="150px">
        <el-form-item label="文章题目">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="文章内容">
      <!-- 修改为文本域以适应多行文本 -->
      <el-input
        type="textarea"
        v-model="form.content"
        :rows="10" 
        resize="none" 
        show-word-limit 
        :max-length="500" 
      />
    </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </span>
      </template>
    </el-dialog>


    <!-- 修改 -->
    <el-dialog v-model="dialogVisible1" title="修改文章" width="30%">
      <el-form :model="form" label-width="150px">
        <el-form-item label="文章题目">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="文章内容">
      <!-- 修改为文本域以适应多行文本 -->
      <el-input
        type="textarea"
        v-model="form.content"
        :rows="10" 
        resize="none" 
        show-word-limit 
        :max-length="500" 
      />
    </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取消</el-button>
          <el-button type="primary" @click="edit">确定</el-button>
        </span>
      </template>
    </el-dialog>



  </div>

</template>

<style scoped>
.content-column .cell {
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 您希望显示的最大行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
